import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:dio/dio.dart';
import 'package:flutter_homemonitor/generated/json/base/json_convert_content.dart';
import 'package:flutter_homemonitor/model/build_info_entity.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_homemonitor/util/toast.dart';
import 'package:flutter_homemonitor/util/CommonConstant.dart';

import '../model/all_detect_item_entity.dart';
import '../model/detect_item_entity.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

//GetBuildingListByDetectItemId
class _MyHomePageState extends State<MyHomePage> {
  List<String> yearsList = []; //年份
  String? selectedChildYears; // 当前选中的子项ID
  Map<String, bool> expansionStates = {}; //
  Map<String, List<AllDetectItemEntity>> DetectItemList = {}; //
  bool isLoadingDetectItem = true; //是否正在加载项目
  int? selectedChildId; // 当前选中的子项ID
  //所有项目列表
  List<AllDetectItemEntity> DetectItemByLeaderList = [];
  //当前项目下房屋
  List<BuildInfoEntity> BuildInfoList = [];
  @override
  void initState() {
    super.initState();
// 初始化所有父项的展开状态为false
    for (var years in yearsList) {
      expansionStates[years] = false;
    }
    _LoadDetectItemListByLeader('83').then((data) {
      String resJson = json.encode(data); //
      List<dynamic> jsonlist = json.decode(resJson); //转换为dynamic list
      DetectItemByLeaderList = [];
      DetectItemByLeaderList.addAll(getAllDetectItemEntityList(jsonlist));
      Set<String> itemlist = new Set(); //年份Set不重复
      bool hasX = false;
      bool hasOther = false;
      DetectItemByLeaderList.forEach((DetectItemByLeaderItem) {
        if (DetectItemByLeaderItem.itemCode.toString().contains("-")) {
          if (!DetectItemByLeaderItem.itemCode
              .toString()
              .split("-")[0]
              .contains("x")) {
            itemlist
                .add(DetectItemByLeaderItem.itemCode.toString().split("-")[0]);
          } else {
            hasX = true;
          }
        } else {
          hasOther = true;
        }
//          }
      });
      List<String> yearlist = []; //年份
      yearlist.addAll(itemlist);
      print(yearlist.toString());
      yearlist.sort(); //排序
      print(yearlist.toString());

      List<String> years = []; //年份 倒序
      for (int a = yearlist.length - 1; a >= 0; a--) {
        years.add(yearlist[a]);
        expansionStates[yearlist[a]] = false;
        DetectItemList[yearlist[a]] = DetectItemByLeaderList.where(
            (DetectItem) => DetectItem.itemCode.contains(yearlist[a])).toList();
      }
      if (hasX) {
        years.add("201x");
        expansionStates["201x"] = false;
        DetectItemList["201x"] = DetectItemByLeaderList.where(
            (DetectItem) => DetectItem.itemCode.contains("201x")).toList();
      }
      if (hasOther) {
        years.add("其他");
        expansionStates["其他"] = false;
        DetectItemList["其他"] = DetectItemByLeaderList.where(
            (DetectItem) => !DetectItem.itemCode.contains("-")).toList();
      }

      setState(() {
        yearsList = years;
      });
    });
  }

  Future _LoadDetectItemListByLeader(String id) async {
    try {
      Response response;
      // response = await Dio()
      //     .get(CommonConstant.GetDetectItemListByLeader + "userId=" + id);
      response = await Dio().post(CommonConstant.GetAllItem);

//      print(response.data);
      return response.data;
    } catch (e) {
      print("异常：" + e.toString());
      return null;
    }
  }

  Future _GetBuildingListByDetectItemId(String id) async {
    try {
      print("zlz:url:::" +
          CommonConstant.GetBuildingListByDetectItemId +
          "DetectItemId=" +
          id);
      Response response;
      response = await Dio().post(
          CommonConstant.GetBuildingListByDetectItemId + "DetectItemId=" + id);

      print("zlz:url:::" +
          CommonConstant.GetBuildingListByDetectItemId +
          "DetectItemId=" +
          id);
      // print("zlz:url:::" + response);
      return response.data;
    } catch (e) {
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Row(
        children: [
          Expanded(
            flex: 1,
            child: buildLeftSide(),
          ),
          const SizedBox(
            // 控制分割线宽度和居中
            width: 1, // 分割线粗细
            child: VerticalDivider(
              thickness: 1, // 实际显示的粗细（需与 SizedBox 一致）
              color: Colors.grey, // 颜色
            ),
          ),
          Expanded(
            flex: 2,
            child: buildRightSide(),
          ),
        ],
      ),
    );
  }

  // 构建左边列表
  Widget buildLeftSide() {
    // return Center(child: CircularProgressIndicator());
    return ListView.builder(
        itemCount: yearsList.length,
        itemBuilder: (context, index) {
          final years = yearsList[index];
          return ExpansionTile(
            title: Text(
              years,
              textAlign: TextAlign.center,
            ),
            initiallyExpanded: expansionStates[years] ?? false,
            onExpansionChanged: (expanded) {
              // toggleExpansion(years);
              expansionStates[years] = !expansionStates[years]!;
            },
            children: DetectItemList[years]!.map((item) {
              return ListTile(
                title: Text(item.itemCode),
                onTap: () => onChildSelected(item.id),
                selected: selectedChildId == item.id,
              );
            }).toList(),
          );
        });
  }

  void onChildSelected(int childId) {
    setState(() {
      selectedChildId = childId;
    });
    print("zlz:::" + childId.toString());
    print("zlz::TEST:" + childId.toString());
    _GetBuildingListByDetectItemId(childId.toString()).then((data) {
      if (data != null) {
        print("zlz::TEST:777777");
        String resJson = json.encode(data); //
        List<dynamic> jsonlist = json.decode(resJson); //转换为dynamic list
        setState(() {
          BuildInfoList = getBuildInfoList(jsonlist);
        });
      } else {
        print("zlz::TEST:返回为null");
      }
    });
  }

  // 构建右边内容
  Widget buildRightSide() {
    if (BuildInfoList.length == 0) {
      return Center(child: Text('无房屋'));
    } else {
      return ListView.builder(
          itemCount: BuildInfoList.length,
          itemBuilder: (context, index) {
            final bool isLastItem = index == BuildInfoList.length - 1;
            return Column(
                // mainAxisAlignment: MainAxisAlignment.start,
                mainAxisSize: MainAxisSize.max,
                // crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    child: InkWell(
                      child: Center(
                        child: Text(
                          BuildInfoList[index].buildingName,
                          // "这是一段会超出容器范围的中间内容需要隐藏,Flutter中间内容溢出隐藏解决方案",
                          textAlign: TextAlign.center,
                          style: TextStyle(fontSize: 18),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      onTap: () => {
                        print(BuildInfoList[index].id),
                        Toast.toast(
                            context, BuildInfoList[index].buildingName, 4, 5)
                      },
                    ),
                    // decoration: BoxDecoration(),
                    height: 50,
                    // clipBehavior: Clip.antiAlias
                  ),
                  if (!isLastItem)
                    Container(
                      height: 1,
                      color: Colors.grey[300],
                      margin: const EdgeInsets.only(bottom: 8),
                    )
                ]);
          });
    }
    // if (selectedChildId == null) {
    //   return Center(child: Text('请选择子项'));
    // }
    // return FutureBuilder<ContentData>(
    //   future: fetchContent(selectedChildId!),
    //   builder: (context, snapshot) {
    //     if (snapshot.connectionState == ConnectionState.waiting) {
    //       return Center(child: CircularProgressIndicator());
    //     } else if (snapshot.hasError) {
    //       return Center(child: Text('错误: ${snapshot.error}'));
    //     } else if (!snapshot.hasData) {
    //       return Center(child: Text('无数据'));
    //     } else {
    //       return DisplayContent(snapshot.data!);
    //     }
    //   },
    // );
  }
}
